package com.mobile.collect.activitys;

import android.content.Intent;
import android.os.Environment;
import android.view.View;
import android.widget.Button;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.mobile.collect.R;
import com.mobile.collect.beans.DeviceInfo;
import com.mobile.collect.beans.DevicePicInfo;
import com.mobile.collect.beans.DevicePointInfo;
import com.mobile.collect.db.EntityManager;
import com.mobile.collect.dialogs.SubmitTipDialog;
import com.mobile.collect.present.BasePresent;

import java.io.File;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.droidlover.xdroidmvp.kit.Kits;
import cn.droidlover.xdroidmvp.kit.NLog;
import cn.droidlover.xdroidmvp.mvp.XActivity;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

public class BackUpActivity extends XActivity<BasePresent> {

    @BindView(R.id.backUpBtn)
    Button backUpBtn;
    @BindView(R.id.importBtn)
    Button importBtn;
    String dataDir;

    @Override
    public int getContentViewId() {
        return R.layout.activity_backup;
    }

    @Override
    public void getDataFromServer() {

    }

    @Override
    public void getIntentData() {

    }

    @Override
    public void initView() {
        super.initView();
        titleTv.setText("备份与导入");
        dataDir = Environment.getExternalStorageDirectory() + "/" + getString(R.string.app_name) + "/备份/";
        Kits.File.makeFolders(dataDir);
    }


    @Override
    public BasePresent newP() {
        return new BasePresent();
    }

    @OnClick({R.id.backUpBtn, R.id.importBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.backUpBtn:
                startActivity(new Intent(BackUpActivity.this, BackUpDataActivity.class));

//                backUp();
                break;
            case R.id.importBtn:
                showTip();
                break;
        }
    }

    private void showTip() {
        SubmitTipDialog submitTipDialog = new SubmitTipDialog(this, new SubmitTipDialog.SlectClickListener() {
            @Override
            public void submitClick() {
                startActivity(new Intent(BackUpActivity.this, ImportDataActivity.class));
            }

            @Override
            public void cancelClick() {

            }
        }, "请谨慎操作，导入后现有数据将会被清除替换成以往备份的数据。您可以先备份当前数据后在进行导入。是否继续导入？");
        submitTipDialog.show();
    }


    private void backUp() {
        showLoadDialog();
        Observable.create(new Observable.OnSubscribe<Object>() {
            @Override
            public void call(Subscriber<? super Object> subscriber) {
                String backTime = Kits.Date.getYmdhms3(Calendar.getInstance().getTimeInMillis())+"_backup";
                String exportPath = dataDir + backTime
                        + "/data/";
                String backPicPath = dataDir + backTime
                        + "/pic/";
                Kits.File.deleteFile(exportPath);
                Kits.File.deleteFile(backPicPath);

                Kits.File.makeFolders(exportPath);
                Kits.File.makeFolders(backPicPath);
                List<DeviceInfo> list = EntityManager.getInstance().queryAllDeviceInfo();
                JsonArray jsonArray = new JsonArray();
                for (DeviceInfo deviceInfo : list) {
                    NLog.d("backUp", deviceInfo.toString());
                    JsonObject jsonObject = new JsonObject();
                    jsonObject.addProperty("_ID", deviceInfo.get_ID());
                    jsonObject.addProperty("deviceName", deviceInfo.getDeviceName());
                    jsonObject.addProperty("deviceNo", deviceInfo.getDeviceNo());
                    jsonObject.addProperty("deviceDes", deviceInfo.getDeviceDes());
                    jsonObject.addProperty("deviceCompany", deviceInfo.getDeviceCompany());
                    jsonObject.addProperty("createUser", deviceInfo.getCreateUser());
                    jsonObject.addProperty("createTime", deviceInfo.getCreateTime());
                    jsonObject.addProperty("editTime", deviceInfo.getEditTime());
                    jsonObject.addProperty("hadExport", deviceInfo.getHadExport());
                    jsonObject.addProperty("isMerge", deviceInfo.isMerge());
                    jsonArray.add(jsonObject);
                }
                Gson gson = new Gson();
                String deviceInfos = gson.toJson(jsonArray);

                String deviceFileName = exportPath + "devices.json";
                Kits.File.writeFile(deviceFileName, deviceInfos, false);


                jsonArray = new JsonArray();
                List<DevicePicInfo> picList = EntityManager.getInstance().queryAllDevicePic();
                for (DevicePicInfo picInfo : picList) {
                    NLog.d("backUp", picInfo.toString());
                    JsonObject jsonObject = new JsonObject();
                    jsonObject.addProperty("_ID", picInfo.get_ID());
                    jsonObject.addProperty("parentId", picInfo.getParentId());
                    jsonObject.addProperty("unitName", picInfo.getUnitName());
                    jsonObject.addProperty("deviceName", picInfo.getDeviceName());
                    jsonObject.addProperty("distance", picInfo.getDistance());
                    jsonObject.addProperty("reference", picInfo.getReference());
                    jsonObject.addProperty("label", picInfo.getLabel());
                    jsonObject.addProperty("direction", picInfo.getDirection());
                    jsonObject.addProperty("floor", picInfo.getFloor());
                    jsonObject.addProperty("status", picInfo.getStatus());
                    jsonObject.addProperty("picPath", picInfo.getPicPath());
                    jsonObject.addProperty("picNo", picInfo.getPicNo());
                    jsonObject.addProperty("picBitMapWidth", picInfo.getPicBitMapWidth());
                    jsonObject.addProperty("picBitmapHeight", picInfo.getPicBitmapHeight());
                    jsonObject.addProperty("lableIsRepeat", picInfo.getLableIsRepeat());
                    jsonObject.addProperty("isCopy", picInfo.isCopy());
                    jsonObject.addProperty("createTime", picInfo.getCreateTime());
                    jsonArray.add(jsonObject);
                    File file = new File(picInfo.getPicPath());
                    Kits.File.copyFile(picInfo.getPicPath(), backPicPath + file.getName());
                }
                String json = gson.toJson(jsonArray);
                String unitFileName = exportPath + "units.json";
                Kits.File.writeFile(unitFileName, json, false);

                jsonArray = new JsonArray();
                List<DevicePointInfo> pointList = EntityManager.getInstance().queryDevicePointInfo();
                for (DevicePointInfo info : pointList) {
                    NLog.d("backUp", info.toString());
                    JsonObject jsonObject = new JsonObject();
                    jsonObject.addProperty("_ID", info.get_ID());
                    jsonObject.addProperty("parentId", info.getParentId());
                    jsonObject.addProperty("scaleX", info.getScaleX());
                    jsonObject.addProperty("scaleY", info.getScaleY());
                    jsonObject.addProperty("viewWidth", info.getViewWidth());
                    jsonObject.addProperty("viewHeight", info.getViewHeight());
                    jsonObject.addProperty("screenX", info.getScreenX());
                    jsonObject.addProperty("screenY", info.getScreenY());
                    jsonObject.addProperty("pointDircetion", info.getPointDircetion());
                    jsonObject.addProperty("direction", info.getDirection());
                    jsonObject.addProperty("bgType", info.getBgType());
                    jsonObject.addProperty("lineType", info.getLineType());
                    jsonObject.addProperty("lineType2", info.getLineType2());
                    jsonObject.addProperty("deviceName", info.getDeviceName());
                    jsonObject.addProperty("addressNo", info.getAddressNo());
                    jsonObject.addProperty("expendNo", info.getExpendNo());
                    jsonObject.addProperty("diameter", info.getDiameter());
                    jsonObject.addProperty("distence", info.getDistence());
                    jsonObject.addProperty("height", info.getHeight());
                    jsonObject.addProperty("type", info.getType());
                    jsonObject.addProperty("typeEn", info.getTypeEn());
                    jsonObject.addProperty("childType", info.getChildType());
                    jsonObject.addProperty("childTypeEn", info.getChildTypeEn());
                    jsonObject.addProperty("checkHardType", info.getCheckHardType());
                    jsonObject.addProperty("checkHardReason", info.getCheckHardReason());
                    jsonObject.addProperty("dangerCheck", info.getDangerCheck());
                    jsonObject.addProperty("dangerCheckReaseon", info.getDangerCheckReaseon());
                    jsonObject.addProperty("heatPreservation", info.getHeatPreservation());
                    jsonObject.addProperty("additionalDes", info.getAdditionalDes());
                    jsonObject.addProperty("labelName", info.getLabelName());
                    jsonObject.addProperty("deviceCount", info.getDeviceCount());
                    jsonObject.addProperty("status", info.getStatus());
                    jsonObject.addProperty("isNewPoint", info.getIsNewPoint());
                    jsonObject.addProperty("createTime", info.getCreateTime());
                    jsonArray.add(jsonObject);
                }
                json = gson.toJson(jsonArray);
                String pointFileName = exportPath + "point.json";
                Kits.File.writeFile(pointFileName, json, false);
                subscriber.onNext(true);
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Object>() {
            @Override
            public void call(Object o) {
                showToast("备份成功");
                disLoadDialog();
            }
        }, new Action1<Throwable>() {
            @Override
            public void call(Throwable throwable) {
                throwable.printStackTrace();
                showToast("备份失败");
                disLoadDialog();
            }
        });
    }

    @Override
    public boolean isNotWorkConnect() {
        return false;
    }
}
